
 <!DOCTYPE HTML>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
  
    <title>微信企业号发送消息和图片 | Zong&#39;s blog</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=3, minimum-scale=1">
    
    <meta name="author" content="Zong">
    
    <meta name="description" content="微信企业号企业号是微信为企业客户提供的移动应用入口，只有企业通讯录的成员才能关注企业号，分级管理员、保密消息等各种特性确保企业内部信息的安全。企业可自行在企业号中可配置多个服务号，可以连接不同的企业应用系统，只有授权的企业成员才能使用相应的服务号。
以上来自腾讯faq，想了解更多请度娘。然后我们有了">
    
    
    
    
    
    <link rel="icon" href="/img/favicon.ico">
    
    
    <link rel="apple-touch-icon" href="/img/pacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/img/pacman.jpg">
    
    <link rel="stylesheet" href="/css/style.css">
</head>
</html>
  <body>
    <header>
      <div>
		
			<div id="imglogo">
				<a href="/"><img src="/img/logo.svg" alt="Zong&#39;s blog" title="Zong&#39;s blog"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/" title="Zong&#39;s blog">Zong&#39;s blog</a></h1>
				<h2 class="blog-motto">日常积累，技术分享</h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/">Home</a></li>
					
						<li><a href="/archives">Archives</a></li>
					
						<li><a href="/categories/运维">运维</a></li>
					
						<li><a href="/categories/容器架构">容器架构</a></li>
					
					<li>
					
					<form class="search" action="//baidu.com/s" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="text" id="search" name="wd" autocomplete="off" maxlength="20" placeholder="Search" />
                        <input name=tn type=hidden value="bds">
                        <input name=cl type=hidden value="3">
                        <input name=ct type=hidden value="2097152">
						<input type="hidden" name="si" value="www.lstop.pub">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>

    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/2017/03/07/微信企业号发送消息和图片/" title="微信企业号发送消息和图片" itemprop="url">微信企业号发送消息和图片</a>
  </h1>
  <p class="article-author">By
    
      <a href="http://www.lstop.pub" title="Zong">Zong</a>
    </p>
  <p class="article-time">
    <time datetime="2017-03-07T06:04:33.000Z" itemprop="datePublished">2017-03-07</time>
    
  </p>
</header>

	<div class="article-content">
		
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		<ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#微信企业号"><span class="toc-number">1.</span> <span class="toc-text">微信企业号</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#企业号授权（AccessToken）"><span class="toc-number">2.</span> <span class="toc-text">企业号授权（AccessToken）</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#请求说明"><span class="toc-number">2.1.</span> <span class="toc-text">请求说明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参数说明"><span class="toc-number">2.2.</span> <span class="toc-text">参数说明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#权限说明"><span class="toc-number">2.3.</span> <span class="toc-text">权限说明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#返回说明"><span class="toc-number">2.4.</span> <span class="toc-text">返回说明</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#发送消息"><span class="toc-number">3.</span> <span class="toc-text">发送消息</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#请求说明-1"><span class="toc-number">3.1.</span> <span class="toc-text">请求说明</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#发送图片"><span class="toc-number">4.</span> <span class="toc-text">发送图片</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#上传临时素材"><span class="toc-number">4.1.</span> <span class="toc-text">上传临时素材</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#请求说明-2"><span class="toc-number">4.1.1.</span> <span class="toc-text">请求说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#参数说明-1"><span class="toc-number">4.1.2.</span> <span class="toc-text">参数说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#返回说明-1"><span class="toc-number">4.1.3.</span> <span class="toc-text">返回说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#上传的媒体文件限制"><span class="toc-number">4.1.4.</span> <span class="toc-text">上传的媒体文件限制</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#发送图片给公众号"><span class="toc-number">5.</span> <span class="toc-text">发送图片给公众号</span></a></li></ol>
		</div>
		
		<h1 id="微信企业号"><a href="#微信企业号" class="headerlink" title="微信企业号"></a>微信企业号</h1><p>企业号是微信为企业客户提供的移动应用入口，只有企业通讯录的成员才能关注企业号，分级管理员、保密消息等各种特性确保企业内部信息的安全。<br>企业可自行在企业号中可配置多个服务号，可以连接不同的企业应用系统，只有授权的企业成员才能使用相应的服务号。</p>
<p>以上来自腾讯faq，想了解更多请度娘。<br>然后我们有了个企业号后，就能使用微信提供的api进行操作了，最经典的是发送消息。</p>
<h1 id="企业号授权（AccessToken）"><a href="#企业号授权（AccessToken）" class="headerlink" title="企业号授权（AccessToken）"></a>企业号授权（AccessToken）</h1><p>首先我们要经过授权，就是说要获得这个企业号的操作权限，通过获取AccessToken体现。<br>AccessToken是企业号的全局唯一票据，调用接口时需携带AccessToken。<br>AccessToken需要用CorpID和Secret来换取，不同的Secret会返回不同的AccessToken。</p>
<h2 id="请求说明"><a href="#请求说明" class="headerlink" title="请求说明"></a>请求说明</h2><p>Https请求方式: GET<br><a href="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=id&corpsecret=secrect" target="_blank" rel="noopener">https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=id&amp;corpsecret=secrect</a></p>
<h2 id="参数说明"><a href="#参数说明" class="headerlink" title="参数说明"></a>参数说明</h2><table>
<thead>
<tr>
<th>参数</th>
<th>必须</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>corpid</td>
<td>是</td>
<td>企业Id</td>
</tr>
<tr>
<td>corpsecret</td>
<td>是</td>
<td>管理组的凭证密钥</td>
</tr>
</tbody></table>
<h2 id="权限说明"><a href="#权限说明" class="headerlink" title="权限说明"></a>权限说明</h2><p>每个secret代表了对应用、通讯录的不同权限；不同的管理组拥有不同的secret。</p>
<h2 id="返回说明"><a href="#返回说明" class="headerlink" title="返回说明"></a>返回说明</h2><p>a)正确的Json返回结果:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">   &quot;access_token&quot;: &quot;accesstoken000001&quot;,</span><br><span class="line">   &quot;expires_in&quot;: 7200</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>access_token</td>
<td>获取到的凭证。长度为64至512个字节</td>
</tr>
<tr>
<td>expires_in</td>
<td>凭证的有效时间（秒）</td>
</tr>
</tbody></table>
<p>b)错误的Json返回示例:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">   &quot;errcode&quot;: 43003,</span><br><span class="line">   &quot;errmsg&quot;: &quot;require https&quot;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结合以上信息，我们可以很容易使用python写出代码</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding: utf-8</span></span><br><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WeixinMsg</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, corpid, corpsecret)</span>:</span></span><br><span class="line">        self.__corpsecret = corpsecret</span><br><span class="line">        self.__corpid = corpid</span><br><span class="line">        self.__token = self.__getToken()</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__getToken</span><span class="params">(self)</span>:</span></span><br><span class="line">        gettoken_url = <span class="string">'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=&#123;0&#125;&amp;corpsecret=&#123;1&#125;'</span>.format(self.__corpid, self.__corpsecret)</span><br><span class="line">        r = requests.get(gettoken_url)</span><br><span class="line">        <span class="keyword">if</span> r.status_code == <span class="number">200</span>:</span><br><span class="line">            <span class="keyword">return</span> r.json()[<span class="string">"access_token"</span>]</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> r.status_code</span><br></pre></td></tr></table></figure>

<h1 id="发送消息"><a href="#发送消息" class="headerlink" title="发送消息"></a>发送消息</h1><p>也是经典的场景，通过构造特定的json数据格式传送到微信api来实现<br>首先传递给企业号api的json格式是这个：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">   &quot;touser&quot;: &quot;UserID1|UserID2|UserID3&quot;,</span><br><span class="line">   &quot;toparty&quot;: &quot; PartyID1 | PartyID2 &quot;,</span><br><span class="line">   &quot;totag&quot;: &quot; TagID1 | TagID2 &quot;,</span><br><span class="line">   &quot;msgtype&quot;: &quot;text&quot;,</span><br><span class="line">   &quot;agentid&quot;: 1,</span><br><span class="line">   &quot;text&quot;: &#123;</span><br><span class="line">       &quot;content&quot;: &quot;Holiday Request For Pony(http://xxxxx)&quot;</span><br><span class="line">   &#125;,</span><br><span class="line">   &quot;safe&quot;:0</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<table>
<thead>
<tr>
<th>参数</th>
<th>必须</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>touser</td>
<td>否</td>
<td>成员ID列表（消息接收者，多个接收者用‘</td>
</tr>
<tr>
<td>toparty</td>
<td>否</td>
<td>部门ID列表，多个接收者用‘</td>
</tr>
<tr>
<td>totag</td>
<td>否</td>
<td>标签ID列表，多个接收者用‘</td>
</tr>
<tr>
<td>msgtype</td>
<td>是</td>
<td>消息类型，此时固定为：text （支持消息型应用跟主页型应用）</td>
</tr>
<tr>
<td>agentid</td>
<td>是</td>
<td>企业应用的id，整型。可在应用的设置页面查看</td>
</tr>
<tr>
<td>content</td>
<td>是</td>
<td>消息内容，最长不超过2048个字节，注意：主页型应用推送的文本消息在微信端最多只显示20个字（包含中英文）</td>
</tr>
<tr>
<td>safe</td>
<td>否</td>
<td>表示是否是保密消息，0表示否，1表示是，默认0</td>
</tr>
</tbody></table>
<p>其他消息类型可以看<a href="http://qydev.weixin.qq.com/wiki/index.php?title=%E6%B6%88%E6%81%AF%E7%B1%BB%E5%9E%8B%E5%8F%8A%E6%95%B0%E6%8D%AE%E6%A0%BC%E5%BC%8F" target="_blank" rel="noopener">api文档</a></p>
<h2 id="请求说明-1"><a href="#请求说明-1" class="headerlink" title="请求说明"></a>请求说明</h2><p>Https请求方式: POST<br><a href="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN" target="_blank" rel="noopener">https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN</a></p>
<p>消息型应用支持文本、图片、语音、视频、文件、图文等消息类型。主页型应用只支持文本消息类型，且文本长度不超过20个字。</p>
<p>代码示例如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding: utf-8</span></span><br><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WeixinMsg</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, corpid, corpsecret)</span>:</span></span><br><span class="line">        self.__corpsecret = corpsecret</span><br><span class="line">        self.__corpid = corpid</span><br><span class="line">        self.__token = self.__getToken()</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__getToken</span><span class="params">(self)</span>:</span></span><br><span class="line">        gettoken_url = <span class="string">'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=&#123;0&#125;&amp;corpsecret=&#123;1&#125;'</span>.format(self.__corpid, self.__corpsecret)</span><br><span class="line">        r = requests.get(gettoken_url)</span><br><span class="line">        <span class="keyword">if</span> r.status_code == <span class="number">200</span>:</span><br><span class="line">            <span class="keyword">return</span> r.json()[<span class="string">"access_token"</span>]</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> r.status_code</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">send</span><span class="params">(self, user, content)</span>:</span></span><br><span class="line">        send_url = <span class="string">'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s'</span>% self.__token</span><br><span class="line">        send_values = <span class="string">'''&#123;</span></span><br><span class="line"><span class="string">            "touser": "%s",   </span></span><br><span class="line"><span class="string">            "msgtype":"text",</span></span><br><span class="line"><span class="string">            "agentid": 1,</span></span><br><span class="line"><span class="string">            "text":&#123;</span></span><br><span class="line"><span class="string">                "content": "%s"</span></span><br><span class="line"><span class="string">               &#125;,</span></span><br><span class="line"><span class="string">            "safe": 0</span></span><br><span class="line"><span class="string">            &#125;'''</span> % (user, content)</span><br><span class="line">        r = requests.post(send_url, data=send_values, headers = &#123;<span class="string">"Content-Type"</span>: <span class="string">"application/json; charset=utf-8"</span>&#125;)</span><br><span class="line">        <span class="keyword">return</span> r.json()[<span class="string">"errcode"</span>]</span><br></pre></td></tr></table></figure>

<h1 id="发送图片"><a href="#发送图片" class="headerlink" title="发送图片"></a>发送图片</h1><p>发送图片比发送文本消息复杂一点，首先需要把图片上传到微信，微信把这个叫素材，素材不单指图片，还有语音、视频、普通文件。素材分临时素材和永久素材，临时素材保存3天。</p>
<h2 id="上传临时素材"><a href="#上传临时素材" class="headerlink" title="上传临时素材"></a>上传临时素材</h2><h3 id="请求说明-2"><a href="#请求说明-2" class="headerlink" title="请求说明"></a>请求说明</h3><p>Https请求方式: POST<br><a href="https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&amp;type=TYPE" target="_blank" rel="noopener">https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&amp;type=TYPE</a></p>
<h3 id="参数说明-1"><a href="#参数说明-1" class="headerlink" title="参数说明"></a>参数说明</h3><table>
<thead>
<tr>
<th>参数</th>
<th>必须</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>access_token</td>
<td>是</td>
<td>调用接口凭证</td>
</tr>
<tr>
<td>type</td>
<td>是</td>
<td>媒体文件类型，分别有图片（image）、语音（voice）、视频（video），普通文件(file)</td>
</tr>
<tr>
<td>media</td>
<td>是</td>
<td>form-data中媒体文件标识，有filename、filelength、content-type等信息</td>
</tr>
</tbody></table>
<h3 id="返回说明-1"><a href="#返回说明-1" class="headerlink" title="返回说明"></a>返回说明</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">   &quot;type&quot;: &quot;image&quot;,</span><br><span class="line">   &quot;media_id&quot;: &quot;1G6nrLmr5EC3MMb_-zK1dDdzmd0p7cNliYu9V5w7o8K0&quot;,</span><br><span class="line">   &quot;created_at&quot;: &quot;1380000000&quot;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>type</td>
<td>媒体文件类型，分别有图片（image）、语音（voice）、视频（video）,普通文件(file)</td>
</tr>
<tr>
<td>media_id</td>
<td>媒体文件上传后获取的唯一标识。最大长度为256字节</td>
</tr>
<tr>
<td>created_at</td>
<td>媒体文件上传时间戳</td>
</tr>
</tbody></table>
<h3 id="上传的媒体文件限制"><a href="#上传的媒体文件限制" class="headerlink" title="上传的媒体文件限制"></a>上传的媒体文件限制</h3><ul>
<li>所有文件size必须大于5个字节</li>
<li>图片（image）:2MB，支持JPG,PNG格式</li>
<li>语音（voice）：2MB，播放长度不超过60s，支持AMR格式</li>
<li>视频（video）：10MB，支持MP4格式</li>
<li>普通文件（file）：20MB</li>
</ul>
<p>代码示例如下：<br>使用requests的post方法，可以方便的上传，headers会自动设置成form-data。Mfile是我们要上传图片的路径，必须可读，这样上传后我们就得到了media_id。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding: utf-8</span></span><br><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="keyword">from</span> os.path <span class="keyword">import</span> sep, getsize</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WeixinMedia</span><span class="params">(object)</span>:</span></span><br><span class="line">    WEIXIN_TOKEN = <span class="string">''</span></span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, Weixin)</span>:</span></span><br><span class="line">        self.__Weixin = Weixin</span><br><span class="line">        self.refershWXToken()</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">refershWXToken</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">global</span> WEIXIN_TOKEN</span><br><span class="line">        WEIXIN_TOKEN = self.__Weixin.token</span><br><span class="line">        </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">upload</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WeixinTmpMedia</span><span class="params">(WeixinMedia)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, Weixin)</span>:</span></span><br><span class="line">        super(WeixinTmpMedia, self).__init__(Weixin)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">uploadImage</span><span class="params">(self, Mfile)</span>:</span></span><br><span class="line">        <span class="comment"># 图片（image）:2MB，支持JPG,PNG格式</span></span><br><span class="line">        upurl = <span class="string">'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=&#123;&#125;&amp;type=image'</span>.format(WEIXIN_TOKEN)</span><br><span class="line">        f = open(Mfile, <span class="string">'rb'</span>)</span><br><span class="line">        suf = f.name.split(<span class="string">'.'</span>)[<span class="number">-1</span>].lower()</span><br><span class="line">        <span class="keyword">if</span> suf &lt;&gt; <span class="string">'jpg'</span> <span class="keyword">and</span> suf &lt;&gt; <span class="string">'png'</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">'Not a image file!'</span></span><br><span class="line">        <span class="keyword">elif</span> getsize(Mfile) &gt; <span class="number">2097152L</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">'Image file too large!'</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            files = &#123;<span class="string">'file'</span>: (f.name.split(sep)[<span class="number">-1</span>], f)&#125;</span><br><span class="line">            r = requests.post(upurl, files=files)</span><br><span class="line">        f.close()</span><br><span class="line">        <span class="keyword">if</span> <span class="string">'media_id'</span> <span class="keyword">in</span> r.json():</span><br><span class="line">            <span class="keyword">return</span> r.json()[<span class="string">'media_id'</span>]</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="string">'errcode: &#123;&#125;, errmsg: &#123;&#125;'</span>.format(r.json()[<span class="string">'errcode'</span>], r.json()[<span class="string">'errmsg'</span>])</span><br></pre></td></tr></table></figure>

<h1 id="发送图片给公众号"><a href="#发送图片给公众号" class="headerlink" title="发送图片给公众号"></a>发送图片给公众号</h1><p>我们改造一下之前的代码，把消息抽象出来，消息可以是文本和图片，他们共同点是token和send方法，传入的weixin类带有token：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding: utf-8</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WeixinMsg</span><span class="params">(object)</span>:</span></span><br><span class="line">    WEIXIN_TOKEN = <span class="string">''</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, Weixin)</span>:</span></span><br><span class="line">        self.__Weixin = Weixin</span><br><span class="line">        self.refershWXToken()</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">refershWXToken</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">global</span> WEIXIN_TOKEN</span><br><span class="line">        WEIXIN_TOKEN = self.__Weixin.token</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">send</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>

<p>发送图片代码继承上面的消息类：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WeixinImg</span><span class="params">(WeixinMsg)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, Weixin)</span>:</span></span><br><span class="line">        super(WeixinImg, self).__init__(Weixin)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">send</span><span class="params">(self, user, mediaID)</span>:</span></span><br><span class="line">        send_url = <span class="string">'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=&#123;&#125;'</span></span><br><span class="line">        send_values = <span class="string">'''&#123;</span></span><br><span class="line"><span class="string">            "touser": "%s",   </span></span><br><span class="line"><span class="string">            "msgtype":"image",</span></span><br><span class="line"><span class="string">            "agentid": 1,</span></span><br><span class="line"><span class="string">            "image":&#123;</span></span><br><span class="line"><span class="string">                "media_id": "%s"</span></span><br><span class="line"><span class="string">               &#125;,</span></span><br><span class="line"><span class="string">            "safe": 0</span></span><br><span class="line"><span class="string">            &#125;'''</span> % (user, mediaID)</span><br><span class="line">        r = requests.post(send_url.format(WEIXIN_TOKEN), data=send_values, headers = &#123;<span class="string">"Content-Type"</span>: <span class="string">"application/json; charset=utf-8"</span>&#125;)</span><br><span class="line">        <span class="keyword">return</span> r.json()[<span class="string">"errcode"</span>]</span><br></pre></td></tr></table></figure>

<p>这样就能发生图片给关注公众号的人了。</p>
  
	</div>
		<footer class="article-footer clearfix">

  <div class="article-tags">
  
  <span></span> <a href="/tags/Python/">Python</a><a href="/tags/微信企业号/">微信企业号</a>
  </div>


<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/categories/运维/">运维</a>
</div>



<div class="article-share" id="share">

  <div data-url="http://www.lstop.pub/2017/03/07/微信企业号发送消息和图片/" data-title="微信企业号发送消息和图片 | Zong&#39;s blog" data-tsina="" class="share clearfix">
  </div>

</div>
</footer>   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/2017/03/14/logback发送日志到filebeat/" title="logback发送日志到filebeat">
  <strong>PREVIOUS:</strong><br/>
  <span>
  logback发送日志到filebeat</span>
</a>
</div>


<div class="next">
<a href="/2017/03/01/zabbix-rest-api开发（登录）/"  title="zabbix rest api开发（登录）">
 <strong>NEXT:</strong><br/> 
 <span>zabbix rest api开发（登录）
</span>
</a>
</div>

</nav>

	
</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
  <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#微信企业号"><span class="toc-number">1.</span> <span class="toc-text">微信企业号</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#企业号授权（AccessToken）"><span class="toc-number">2.</span> <span class="toc-text">企业号授权（AccessToken）</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#请求说明"><span class="toc-number">2.1.</span> <span class="toc-text">请求说明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参数说明"><span class="toc-number">2.2.</span> <span class="toc-text">参数说明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#权限说明"><span class="toc-number">2.3.</span> <span class="toc-text">权限说明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#返回说明"><span class="toc-number">2.4.</span> <span class="toc-text">返回说明</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#发送消息"><span class="toc-number">3.</span> <span class="toc-text">发送消息</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#请求说明-1"><span class="toc-number">3.1.</span> <span class="toc-text">请求说明</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#发送图片"><span class="toc-number">4.</span> <span class="toc-text">发送图片</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#上传临时素材"><span class="toc-number">4.1.</span> <span class="toc-text">上传临时素材</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#请求说明-2"><span class="toc-number">4.1.1.</span> <span class="toc-text">请求说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#参数说明-1"><span class="toc-number">4.1.2.</span> <span class="toc-text">参数说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#返回说明-1"><span class="toc-number">4.1.3.</span> <span class="toc-text">返回说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#上传的媒体文件限制"><span class="toc-number">4.1.4.</span> <span class="toc-text">上传的媒体文件限制</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#发送图片给公众号"><span class="toc-number">5.</span> <span class="toc-text">发送图片给公众号</span></a></li></ol>
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  
<div class="tagslist">
	<p class="asidetitle">Tags</p>
		<ul class="clearfix">
		
			<li><a href="/tags/Airtest/" title="Airtest">Airtest<sup>1</sup></a></li>
		
			<li><a href="/tags/DNS/" title="DNS">DNS<sup>1</sup></a></li>
		
			<li><a href="/tags/GitLab/" title="GitLab">GitLab<sup>1</sup></a></li>
		
			<li><a href="/tags/K8s/" title="K8s">K8s<sup>8</sup></a></li>
		
			<li><a href="/tags/Linux/" title="Linux">Linux<sup>1</sup></a></li>
		
			<li><a href="/tags/MongoDB/" title="MongoDB">MongoDB<sup>2</sup></a></li>
		
			<li><a href="/tags/OpenWrt/" title="OpenWrt">OpenWrt<sup>1</sup></a></li>
		
			<li><a href="/tags/Python/" title="Python">Python<sup>2</sup></a></li>
		
			<li><a href="/tags/RabbitMQ/" title="RabbitMQ">RabbitMQ<sup>1</sup></a></li>
		
			<li><a href="/tags/calico/" title="calico">calico<sup>1</sup></a></li>
		
			<li><a href="/tags/cdn/" title="cdn">cdn<sup>1</sup></a></li>
		
			<li><a href="/tags/docker/" title="docker">docker<sup>3</sup></a></li>
		
			<li><a href="/tags/docker-registry/" title="docker registry">docker registry<sup>1</sup></a></li>
		
			<li><a href="/tags/elasticsearch/" title="elasticsearch">elasticsearch<sup>3</sup></a></li>
		
			<li><a href="/tags/elk/" title="elk">elk<sup>3</sup></a></li>
		
			<li><a href="/tags/k8s/" title="k8s">k8s<sup>3</sup></a></li>
		
			<li><a href="/tags/kubernetes/" title="kubernetes">kubernetes<sup>1</sup></a></li>
		
			<li><a href="/tags/nginx/" title="nginx">nginx<sup>1</sup></a></li>
		
			<li><a href="/tags/python/" title="python">python<sup>1</sup></a></li>
		
			<li><a href="/tags/tomcat/" title="tomcat">tomcat<sup>1</sup></a></li>
		
		</ul>
</div>


  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
      <li><a href="http://www.v2ex.com/?r=zong400" target="_blank" title="V2EX">V2EX</a></li>
      <li><a href="http://hexo.io" target="_blank" title="Hexo">Hexo</a></li>
	  <li><a href="https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=s0bh6uzq" target="_blank" title="阿里云">阿里云</a></li>
	  <li><a href="https://cloud.tencent.com/redirect.php?redirect=1014&cps_key=5bd9deb84d4d9f34b65fb934e12d03e3&from=console" target="_blank" title="腾讯云">腾讯云</a></li>
    </ul>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	
	<div class="social-font" class="clearfix">
		
		
		
		
	</div>
		<p class="copyright">Hosted by <a href="https://pages.coding.me/" target="_blank" title="Coding Pages">Coding Pages</a></p>
		<p class="copyright">Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wizicer/iceman" target="_blank" title="Iceman">Iceman</a> © 2020 
		
		<a href="http://www.lstop.pub" target="_blank" title="Zong">Zong</a>
		
		</p>
</div>
</footer>
    <script src="//cdn.staticfile.org/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else
    {
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      h  = $('article h2')
      ah = $('article h2'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  if(ah.length==0){
    t.css('display','none');
  }else{
    c.click(function(){
      ta.css('display', 'block').addClass('fadeIn');
    });
    o.click(function(){
      ta.css('display', 'none');
    });
    $(window).scroll(function(){
      ta.css("top",Math.max(140,320-$(this).scrollTop()));
    });
  };
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina');
  var html = [
  '<a href="#" class="overlay" id="qrcode"></a>',
  '<div class="qrcode clearfix"><span>扫描二维码分享到微信朋友圈</span><a class="qrclose" href="#share"></a><strong>Loading...Please wait</strong><img id="qrcode-pic" data-src="http://s.jiathis.com/qrcode.php?url=' + encodedUrl + '"/></div>',
  '<a href="#textlogo" class="article-back-to-top" title="Top"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="QRcode"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="Weibo"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);
  $('.article-share-qrcode').click(function(){
    var imgSrc = $('#qrcode-pic').attr('data-src');
    $('#qrcode-pic').attr('src', imgSrc);
    $('#qrcode-pic').load(function(){
        $('.qrcode strong').text(' ');
    });
  });
});     
</script>









  </body>
</html>

